#include "bezier.h"
#include <math.h>

Bezier::Bezier()
{

}

//定义一个三阶贝塞尔曲线函数，t的范围在[0,1]；
//输入P0, P1, P2, P3，分别为起始点，控制1点，控制2点，终止点；
//https://blog.csdn.net/u011643833/article/details/78540554
POINT Bezier::bezierPoint(double t, POINT p0, POINT p1, POINT p2, POINT p3)
{
    double u = 1 - t;
    double tt = t * t;
    double uu = u * u;
    double uuu = uu * u;
    double ttt = tt * t;

    POINT p;
    p.x = uuu * p0.x;
    p.y = uuu * p0.y;

    p.x += 3 * uu * t * p1.x;
    p.y += 3 * uu * t * p1.y;

    p.x += 3 * u * tt * p2.x;
    p.y += 3 * u * tt * p2.y;

    p.x += ttt * p3.x;
    p.y += ttt * p3.y;

    return p;
}

int Bezier::getBezierPoints(POINT p0, POINT p1, POINT p2, POINT p3, int pointCount, std::vector<POINT> &pointsOut)
{
    double deltaT=1.0/pointCount;
    pointsOut.clear();
    POINT tmpPoint;
    for(int i=0;i<=pointCount;i++)
    {
        tmpPoint=bezierPoint(deltaT*i,p0,p1,p2,p3);
        pointsOut.push_back(tmpPoint);
    }
    return 1;
}


double Bezier::getBezier_length(POINT p0, POINT p1, POINT p2, POINT p3, int pointCount)
{
    //取点 默认 30个
    pointCount = 30;
    double length = 0.0;
    POINT lastPoint = bezierPoint(0.0 / (double)pointCount, p0, p1, p2, p3);
    for (int i = 1; i <= pointCount; i++)
    {
        POINT point = bezierPoint((double)i / (double)pointCount, p0, p1, p2, p3);
        length += sqrt((point.x - lastPoint.x) * (point.x - lastPoint.x) + (point.y - lastPoint.y) * (point.y - lastPoint.y));
        lastPoint = point;
    }
    return length;
}
